<template>
  <div class="app-container">

    <!-- 顶部工具栏1   -->
    <div class="" style="margin-bottom: 10px;width: 100%;height:40px;">


      <span
        style="float: left;color: black;font-family:'Microsoft YaHei';line-height:40px;display:block;width:400px;font-size:30px;font-weight: bold">操作日期：{{localDate| parseTime('{y}-{m}-{d}')}}</span>
      <el-radio-group style="float: right;" v-model="radio1" @change="changePlatform">
        <el-radio-button v-for="(pt,index) in PT_TYPE" :label="pt.id">{{pt.display_name}}</el-radio-button>
        <!--        <el-radio-button label="电信"></el-radio-button>-->
        <!--        <el-radio-button label="联通"></el-radio-button>-->
      </el-radio-group>
    </div>
    <!-- 顶部工具栏2   -->
    <div class="filter-container">


<!--      <el-button @click="programListDrawer = true" type="primary" classmgt="filter-item">-->
      <el-button @click="isSaveDrag(()=>{programListDrawer = true})" type="primary" class="filter-item">
        排期列表
      </el-button>
      <el-select v-model="listQuery.mediacode" placeholder="筛选条件" clearable style="width: auto" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item"/>
        <!--      <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      </el-select>
      <el-select v-model="listQuery.vtype" placeholder="栏目类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'"
                   :value="item.key"/>
      </el-select>
      <el-input v-model="listQuery.vName" placeholder="请输入搜索关键字" style="width: 300px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <!--    <el-select v-model="listQuery.sort" style="width: 140px" classmgt="filter-item" @change="handleFilter">-->
      <!--      <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--    </el-select>-->
      <!--      <div classmgt="block">-->
      <!--        <span classmgt="demonstration">使用 value-format</span>-->
      <!--        <div classmgt="demonstration">值：{{ selectedData }}</div>-->

      <!--      </div>-->
      <!--      <el-date-picker-->
      <!--        v-model="localDate"-->
      <!--        classmgt="filter-item"-->
      <!--        type="date"-->
      <!--        placeholder="选择日期"-->
      <!--        format="yyyy-MM-dd"-->
      <!--        value-format="yyyy-MM-dd"-->
      <!--        @change="selectDate"></el-date-picker>-->

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-plus"
                 @click="handleCreate">
        新增
      </el-button>

      <el-time-picker
        class="filter-item"
        style="width: 150px"
        v-model="baseTimeHms"
        placeholder="选择时间">
      </el-time-picker>
      <el-button class="filter-item" type="primary" @click="resetTime">
        时间重置
      </el-button>
      <el-button class="filter-item" :type=" isDragged?'danger':'info' " @click="saveDrag">
        拖拽保存
      </el-button>

      <!--    <el-button  :loading="downloadLoading" classmgt="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">-->
      <el-button :loading="downloadLoading" class="filter-item" type="warning " icon="el-icon-upload2"
                 style="float: right">
        导入
      </el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="warning " icon="el-icon-download"
                 style="float: right">
        导出
      </el-button>
      <!--      <el-checkbox v-model="showReviewer" classmgt="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        暂时不用(reviewer)-->
      <!--      </el-checkbox>-->
    </div>

    <!--    <div classmgt="programlist" style="">-->
    <template>
      <el-drawer
        title="节目排期"
        :visible.sync="programListDrawer"
        :before-close="handleCloseProgramList"
        :withHeader="false"
        @open="openProgramList">
        <!--        <div style="background-color: #42b983">-->
        <!--        <span>节目编排</span>-->
        <span v-show="programListLoading" class="el-icon-loading"></span>
        <ul v-if="!programListLoading" class="infinite-list">
          <!--            <li v-for="i in programList" classmgt="infinite-list-item">{{ i }}</li>-->

          <li v-for="(item ,index) in programList" class="infinite-list-item">
            <!--            <li  classmgt="infinite-list-item" >-->
            <!--            <template slot-scope="scope">-->

            <el-button-group>
              <el-button plain type="info" style="width: 150px" icon="el-icon-date">{{item.setdate}}</el-button>
              <el-button type="primary" icon="el-icon-edit" @click="editProgramListData(item,index)"></el-button>
              <!--              <el-button type="primary" icon="el-icon-plus"></el-button>-->
              <el-button type="primary" icon="el-icon-copy-document"></el-button>
<!--              删除按钮-->
              <el-popconfirm
                v-model="visibleProList"
                title="确定要删除这条数据吗？"
                iconColor="red"
                icon="el-icon-warning"
                @onConfirm="handleDeleteProList(item, index)"
                @onCancel="visibleProList=false"
              >
                <el-button slot="reference" type="danger" icon="el-icon-delete"></el-button>
              </el-popconfirm>

            </el-button-group>
            <el-tag
              :type=PRO_LIST_STATE[item.alivestate].type
              :effect=PRO_LIST_STATE[item.alivestate].effect>
              {{ PRO_LIST_STATE[item.alivestate].display_name }}
            </el-tag>
          </li>
          <li style=" list-style-type: none">
            <el-button type="success" icon="el-icon-plus" @click="createProgramBar">新增{{programList.length}}</el-button>
          </li>

        </ul>
        <!--        </div>-->
      </el-drawer>
    </template>
    <!--    </div>-->


    <!--    数据列表-->
    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      ref="dragTable"
      row-key="id"
    >

      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column
        label="ID"
        width="50">
        <template slot-scope="scope">
          <span style="margin-left: 0px">{{ scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        width="180"
        align="center">
        <template slot-scope="scope">
          <!--          <span style="margin-left: 0px">{{ scope.row.stime }}</span>-->
          <!--          <span style="margin-left: 0px">{{ scope.row.playtime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
          <span style="margin-left: 0px">{{ scope.row.playtime}}</span>

        </template>
      </el-table-column>
      <el-table-column
        label="所属栏目"
        width="100"
        align="center">
        <template slot-scope="scope">
          <span style="margin-left: 0px">{{ scope.row.vtype|typeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="视频名称"
        width="180"
        align="center">
        <template slot-scope="scope">
          <span style="margin-left: 0px">{{ scope.row.vname }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="code"
        width="280"
        align="center">
        <template slot-scope="scope">
          <span style="margin-left: 0px">{{ scope.row.mediacode }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="节目时长(秒)"
        width="120"
        align="center">
        <template slot-scope="scope">
          <span style="margin-left: 0px">{{ scope.row.videoleng }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="文件状态"
        width="100"
        align="center">
        <template slot-scope="scope">
          <!--        <el-popover trigger="hover" placement="top">-->
          <!--          <p>姓名: {{ scope.row.name }}</p>-->
          <!--          <p>住址: {{ scope.row.address }}</p>-->
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.ctxstate }}</el-tag>
          </div>
          <!--        </el-popover>-->
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate(scope.row)">修改
            <!--            @click="handleEdit(scope.$index, scope.row)">-->
          </el-button>
          <el-popover
            placement="top"
            width="200"
            v-model="scope.row.visible">
            <p>确定要删除这条数据吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="handleDelete(scope.$index, scope.row)">确定</el-button>
            </div>
            <el-button slot="reference" size="mini" icon="el-icon-delete" type="danger">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>

    </el-table>

    <!--    新增视频数据弹窗-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="栏目" prop="vtype">
          <el-select v-model="temp.vtype" class="filter-item" placeholder="Please select">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name"
                       :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="视频名称" prop="vname">
          <el-input v-model="temp.vname"/>
        </el-form-item>
        <el-form-item label="code" prop="mediacode">
          <el-input v-model="temp.mediacode"/>
        </el-form-item>
        <el-form-item label="节目时长(秒)" prop="videoleng">
          <!--          <el-date-picker v-model="temp.playtime" type="datetime" placeholder="Please pick a date"/>-->
          <!--          <el-date-picker v-model="temp.playtime" type="datetime" placeholder="Please pick a date"/>-->
          <el-input v-model="temp.videoleng"/>

        </el-form-item>
        <el-form-item label="Remark">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea"
                    placeholder="Please input"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!--   新增节目单弹窗 -->
    <el-dialog
      title="创建新节目单"
      :visible.sync="dialogAddProVisible"
      width="30%"
      :before-close="closeAddProgramBar">
      <!--      <span>请选择日期</span>-->
      <!--      <span slot="footer" classmgt="dialog-footer">-->
      <el-date-picker
        v-model="localDateAdd"
        class="filter-item"
        type="date"
        placeholder="选择日期"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        @change="selectDateAddProBar"></el-date-picker>
      <el-button @click="dialogAddProVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirmAddProBar()">确 定</el-button>
      <!--  </span>-->

    </el-dialog>


  </div>
</template>

<script>
  // import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
  import {
    createArticle,
    fetchList,
    updateArticle,
    fetchListProgram,
    updateProgramList,
    delProgramList,
    delVideoTape,
    updateBatchOfSortid

  } from '@/api/article' // waves directive
  // import waves from '@/directive/waves'
  import { parseTime } from '@/utils'
  import { isEmpty } from '@/utils/utilc'
  import Sortable from 'sortablejs'


  // import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  const calendarTypeOptions = [
    { key: 'GD', display_name: '广告' },
    { key: 'SC', display_name: '学校' },
    { key: 'PX', display_name: '培训机构' },
    { key: 'AC', display_name: '动画' },
    { key: 'TE', display_name: '名师' }
  ]

  const PT_TYPE = [
    { id: 0, name: 'yd', display_name: '移动' },
    { id: 1, name: 'dx', display_name: '电信' },
    { id: 2, name: 'lt', display_name: '联通' }
  ]

  /**
   * 节目单状态
   * @type {({display_name: string, type: string}|{display_name: string, type: string}|{display_name: string, type: string}|{display_name: string, type: string})[]}
   */
  const PRO_LIST_STATE = [
    { display_name: '未就绪', type: 'danger', effect: 'dark' },
    { display_name: '就绪', type: 'success', effect: 'plain' },
    { display_name: '已过期', type: 'info', effect: 'dark' },
    { display_name: '未播放', type: 'success', effect: 'light' },
    { display_name: '正在播放', type: 'success', effect: 'dark' },
    { display_name: '已播放', type: 'info', effect: 'plain' }
  ]
  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  const MAX_TIME = 24 * 60 * 60//每日最大时长（秒）

  export default {
    // name: 'ComplexTable',
    // components: { Pagination },
    // directives: { waves },

    props: {
      stickyTop: {
        type: Number,
        default: 0
      },
      zIndex: {
        type: Number,
        default: 1
      },
      className: {
        type: String,
        default: ''
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },

      parseTime: parseTime

    },
    data() {
      return {

        PT_TYPE,//平台分类
        PRO_LIST_STATE,//节目单状态
        platformKey: 0,//平台id
        // radio1: this.PT_TYPE[this.platformKey].display_name,
        radio1: '0',
        localDate: '',//选择操作的日期

        currID_Date:0,//操作日期的ID（以此查找节目单数据）

        //视频数据条
        tempVideoTape:{
          id: undefined,
          importance: 1,
          remark: '',
          playtime: '',
          // playtime2: '',
          vname: '',
          status: 'published',
          vtype: '',
          mediacode: '',
          ctxstate: '0',
          videoleng: '1',

          idate:'',//对应排期单id
          auther:'',//操作人员
          timelog:'',//时间日志
          playstate:'0'//播放状态
        },

        programList: [],
        programListQuery: {
          id: '',
          setdate: '',
          playstate: '',
          timelog: '',
          alivestate: '',
          auther: ''
        },
        tempProList: {
          id: '',
          setdate: '',
          playstate: -1,
          timelog: new Date('yyyy-MM-dd HH:mm:ss'),
          alivestate: 0,
          auther: ''
        },
        programListDrawer: false,
        programListLoading: true,
        timeSetH: 0,//重置小时
        timeSetM: 0,//重置分钟
        timeSetS: 0,//重置秒
        baseTimeDateString: '2020/5/30',//基础日期
        baseTimeSeconds: 0,//基础时间累积 （秒）
        baseTimeHms:'',//基准时间点
        visible: false,
        visibleProList: false,
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          // limit: 20,
          importance: undefined,
          auther: undefined,
          vname: undefined,
          vtype: undefined,
          sort: '+id',
          mediacode: '',
          ctxstate: '',//文件状态
          videoleng: 1,
          playtime: '',
          lasttime: ''//上条节目播放结束时间

          // playtime2: ''
        },
        importanceOptions: ['视频名称', 'mediaCode'],
        calendarTypeOptions,
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          // id: undefined,
          // importance: 1,
          // remark: '',
          // videoleng: '',
          // // playtime2: '',
          // vname: '',//视频名称
          // vtype: '',//栏目
          // ctxstate: '0',
          // mediacode: '',//视频code
          // playtime: '',
          // lasttime_s: '',//上条节目播放结束时间
          //
          // idate:'',//对应排期单id
          // auther:'',//操作人员
          // timelog:'',//时间日志
          // playstate:'0'//播放状态
        },

        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          playtime: [{ type: 'date', required: true, message: 'playtime is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false,

        sortable: null,

        dialogAddProVisible: false,
        localDateAdd: '',//新增日期列表中使用的

        isDragged:false,//是否拖拽修改过排序

      }
    },

    created() {
      // this.radio1 = PT_TYPE[this.platformKey].display_name;
      // this.getListProgram()
      // this.getList()
    },
    methods: {

      getIsAliveDate() {
        return !isEmpty(this.localDate)
      },
      handleEdit(index, row) {
        console.log(index, row)
      },

      /**
       *
       * 删除节目单
       * */
      async handleDelete(index, row) {
        console.log(index, row)
        const data = await delVideoTape(row.id)
        if(data.code=="20000"){
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
          this.resetTimeAll()
        }else{
          this.$notify({
            title: 'Error',
            message: 'Delete Error',
            type: 'error',
            duration: 2000
          })
        }

      },

      // clickDelete(index, row){
      //   this.$set(this.tipVisibles, index, false);
      // },

      sortChange(data) {
        console.log('----------------prop==' + data)
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },

      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'playtime') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      resetTemp() {
        // this.temp = this.tempVideoTape
        this.temp = Object.assign({}, this.tempVideoTape)
        // console.log("resetTemp==="+JSON.stringify(this.tempVideoTape))
      },

      /**
       *
       * 获取排期列表
       * */
      async getListProgram() {
        // const { data } = await fetchListProgram(this.programListQuery)
        const config = await fetchListProgram(this.programListQuery)  //这里应当区分平台

       const {data} = this.handleResponse(config);


        // console.log("getListProgram.data==="+JSON.stringify(data));


        this.programList = data.items
        this.programList.sort(this.sortProgramList)
        this.programListLoading = false
        // console.log('programList.length===' + JSON.stringify(this.programList))
      },


      async getList() {
        this.listLoading = true
        // fetchList(this.listQuery).then(response => {
        //   this.list = response.data.items
        //   this.total = response.data.total
        //
        //   // Just to simulate the time of the request
        //   setTimeout(() => {
        //     this.listLoading = false
        //   }, 1.5 * 1000)
        // })

        // const { data } = await fetchList(this.listQuery)
        const config = await fetchList(this.currID_Date)
        const {data} = this.handleResponse(config);//就为了转一下数据格式,方便本脚本内使用

        this.list = data.items
        this.total = data.total
        this.listLoading = false

        let that = this;
        this.$nextTick(() => {
          // this.$nextTick(function() {
          that.setSort()
          // console.log('getList=1=' + data.items);

          console.log('data=1=' + new Date().toLocaleDateString());
          // console.log('data=2=' + new Date(this.baseTimeDateString).getTime());
          that.resetTimeAll()

        })
      },

      setSort() {
        console.log("setSort==1");

        const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
        let that = this
        console.log("setSort==2");

        this.sortable = Sortable.create(el, {
          ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
          setData: function(dataTransfer) {
            console.log("setSort:setData==")
            // to avoid Firefox bug
            // Detail see : https://github.com/RubaXa/Sortable/issues/1012
            dataTransfer.setData('Text', '')
          },
          onEnd: evt => {
            console.log('-----onEnd-------->' + evt.newIndex + '    ' + evt.oldIndex + ' ')

            console.log(this.list[evt.newIndex].vname+"==="+this.list[evt.oldIndex].vname)
            this.isDragged = true
            const targetRow = this.list.splice(evt.oldIndex, 1)[0]
            this.list.splice(evt.newIndex, 0, targetRow)
            this.resetTimeAll()
          }
        })
      },
      /***
       *
       *搜索按钮
       **/
      handleFilter() {

        console.log("="+this.listQuery.mediacode+"  "+this.listQuery.vtype+"  "+this.listQuery.vname)

        if(isEmpty(this.listQuery.mediacode)&&isEmpty(this.listQuery.vtype)&&isEmpty(this.listQuery.vname)){

          this.$notify({
            title: 'Error',
            message: '筛选条件不能为空',
            type: 'error',
            duration: 2000
          })

        }else{
          if (this.getIsAliveDate()) {
            this.listQuery.page = 1
            this.getList()
          }else{
            this.$notify({
              title: 'Error',
              message: '请选择需要操作的节目单',
              type: 'error',
              duration: 2000
            })
          }
        }


        // if (this.getIsAliveDate()) {
        //   this.listQuery.page = 1
        //   this.getList()
        // } else {
        //   this.$notify({
        //     title: 'Error',
        //     message: '请选择需要编辑的节目单',
        //     type: 'error',
        //     duration: 2000
        //   })
        // }

      },


      /**
       * 新增视频数据
       * */
      handleCreate() {
        if (this.getIsAliveDate()) {
          this.resetTemp()
          this.dialogStatus = 'create'
          this.dialogFormVisible = true
          this.$nextTick(() =>  {
            this.$refs['dataForm'].clearValidate()
          })
        } else {
          this.$notify({
            title: 'Error',
            message: '请选择需要编辑的节目单',
            type: 'error',
            duration: 2000
          })
        }

      },

      /***
       * 工具栏时间重置按钮
       *
       * */
      resetTime() {
        console.log('baseTimeHms==' + this.baseTimeHms)
        let newtime = new Date(this.baseTimeHms);

        let hour = newtime.getHours();
        let mins = newtime.getMinutes();
        let sec = newtime.getSeconds();
        this.timeSetH = hour;
        this.timeSetM = mins;
        this.timeSetS = sec;
        console.log("hour="+hour+" mis="+mins+" sec="+sec);

        //重置所有节目开始时间
        this.resetTimeAll();

      },


      isSaveDrag(callback){
        if(this.isDragged){
          this.$confirm('视频播放顺序已修改，是否保存？','提示',{
            confirmButtonText:'确定',
            cancelButtonText:'取消',
            type:'warning'
          }).then(
            ()=>{
              if(this.saveDrag())
                callback()
            }
          ).catch(
            ()=>{
              this.$message({
                type: 'info',
                message: '已放弃修改'
              });
              // return callback()
              callback();
            }
          )
        }else{
           callback();
        }


      },

      /**
       *
       * 拖拽后保存修改
       * */
     async saveDrag(){

        // let  arr = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')



        if(this.isDragged){

          let arrID_Sortid = new Array();


          for (let i = 0; i < this.list.length; i++) {
            this.list[i].sortid = i;
            // let temp ={id:"",sid:""}
            // temp.id = this.list.id;
            // temp.sid = i;
            arrID_Sortid.push({key:this.list[i].id,value:i});
          }

        console.log("arrID_Sortid="+JSON.stringify(arrID_Sortid))

         // const response  = await updateBatchOfSortid(JSON.stringify(arrID_Sortid))
         const response  = await updateBatchOfSortid(arrID_Sortid)
          if(response.code=="20000"){
            this.isDragged =false;
            this.$notify({
              title: 'Success',
              message: "保存成功",
              type: 'success',
              duration: 2000
            })
            return true;
          }else{
            this.$notify({
              title: 'Error',
              message: "保存失败",
              type: 'error',
              duration: 2000
            })
            return false;
          }


        }
      },


      /***
       *检测视频数据是否合法
       * @param obj 视频数据对象 listquery格式
       * @return boolean
       * */
      checkVideoParam(obj) {
        if (isEmpty(obj.mediacode) || isEmpty(obj.vname) || isEmpty(obj.vtype) || isEmpty(obj.videoleng)) {
          this.$notify({
            title: 'Error',
            message: '数据不能为空',
            type: 'error',
            duration: 2000
          })
          return false
        }
        return true
      },

      /**
       *
       *
       * 是否超过单日最大时长
       *@param addtime 新增时长
       * @param basedate 基准日期 （仅 年月日）无详细时间数据
       *
       * @return boolean
       * */
      checkIsMaxTime(baseseconds, basedate, addtime) {

        if ((baseseconds + addtime) <= (MAX_TIME + basedate)) {
          //允许添加新视频
          return false
        } else {
          //超过单日最大时间长
          this.$notify({
            title: 'Error',
            message: '单日最大播放时长超时' + ((MAX_TIME + basedate) - (baseseconds + addtime)),
            type: 'error',
            duration: 2000
          })
          return true
        }

      },


      /***
       *
       * 创建视频数据
       *
       * */
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 此id对应所属节目单唯一id
            this.temp.idate = this.currID_Date


            this.temp.id = parseInt(Math.random() * 100) + 1024 // mack a id
            // this.temp.id = this.list.length // mack a id
            this.temp.playstate=0;
            this.temp.timelog =parseTime(new Date())
            this.temp.auther = 'vue-admin-template'


            createArticle(this.temp).then(() => {
            console.log("11新增数据："+JSON.stringify(this.temp));

              // this.baseTimeDateString = this.localDate;

              //更新时间
              let setTime = this.timeSetH * 60 * 60 + this.timeSetM * 60 + this.timeSetS
              let newLeng = parseInt(this.temp.videoleng)
              let baseDataSeconds = new Date(this.baseTimeDateString).getTime() / 1000//日期基数
              this.baseTimeSeconds += setTime

              // videoleng: '1',
              //   // playtime2: '',
              //   vname: '',//视频名称
              //   vtype: '',//栏目
              //   ctxstate: '未就绪',
              //   mediacode: '',//视频code
              //   playtime:''

              // if (isEmpty(this.temp.mediacode) || isEmpty(this.temp.vname) || isEmpty(this.temp.vtype) || isEmpty(this.temp.videoleng)) {
              //   this.$notify({
              //     title: 'Error',
              //     message: '数据不能为空',
              //     type: 'error',
              //     duration: 2000
              //   })
              //   return false;
              // }

              if (!this.checkVideoParam(this.temp)) {
                return false
              }

              console.log(this.baseTimeSeconds + '  ' + newLeng + ' baseTimeDateString=' + baseDataSeconds)

              if (this.checkIsMaxTime(this.baseTimeSeconds, newLeng, baseDataSeconds)) {
                this.temp.lasttime_s = this.baseTimeSeconds
                this.baseTimeSeconds += newLeng
                this.temp.playtime = this.myGetTime(this.baseTimeSeconds * 1000, 'full')
                console.log(this.temp.playtime + '  ')

                // updateArticle(this.temp){}
                this.list.push(this.temp)
                this.dialogFormVisible = false
                this.$notify({
                  title: 'Success',
                  message: 'Created Successfully',
                  type: 'success',
                  duration: 2000
                })
              }

              // if ((this.baseTimeSeconds + newLeng) <= (MAX_TIME + baseDataSeconds)) {
              //   // this.list.unshift(this.temp);
              // } else {
              //   this.$notify({
              //     title: '创建失败',
              //     message: '单日最大播放时长超时' + (this.baseTimeSeconds + newLeng),
              //     type: 'error',
              //     duration: 2000
              //   })
              // }

              // this.list.unshift(this.temp)
              // this.dialogFormVisible = false

            })
          }
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['playtime', 'vname', 'vtype', 'importance', 'ctxstate']
          const filterVal = ['playtime', 'vname', 'vtype', 'importance', 'ctxstate']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },

      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        console.log('1修改：' + this.temp.playtime)
        // this.temp.playtime = new Date(this.temp.playtime);
        // this.temp.playtime = this.temp.playtime;
        // console.log('2修改：' + this.temp.playtime)

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            console.log('1updateData==>' + tempData.playtime)

            // tempData.playtime = +new Date(tempData.playtime) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            tempData.playtime = tempData.lasttime_s + parseInt(tempData.videoleng) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            console.log('2updateData==>' + tempData.playtime)



            updateArticle(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
            //   }
            // }

          }
        })
      },

      countTime(i) {
        // let item = this.editListBox.item.list[i]
        // let item = this.data.item.list[i]
        // let time0 = new Date().getTime()
        // if (i === 0) {
        //   let beginTime = this.editListBox.item.date
        //   let shi = this.editListBox.item.shi
        //   let fen = this.editListBox.item.fen
        //   let miao = this.editListBox.item.miao
        //   if (shi < 10) {
        //     shi = '0' + shi
        //   }
        //   if (fen < 10) {
        //     fen = '0' + fen
        //   }
        //   if (miao < 10) {
        //     miao = '0' + miao
        //   }
        //   beginTime += ' ' + shi + ':' + fen + ':' + miao
        //   time0 = new Date(beginTime).getTime()
        //   // let timeEnd = time0 + (item.fen * 60 + item.miao) * 1000;
        //   let timeEnd = time0 + (item.miao * 1000)
        //   item.time1 = beginTime
        //   item.time2 = myGetTime(timeEnd, 'full')
        // } else {
        //   let lastIt = this.editListBox.item.list[i - 1]
        //   time0 = new Date(lastIt.time2).getTime()
        //   let timeEnd = time0 + (item.fen * 60 + item.miao) * 1000
        //   item.time1 = lastIt.time2
        //   item.time2 = myGetTime(timeEnd, 'full')
        // }
      },

      myGetTime(theTime, type) {
        if (!theTime) {
          return ''
        }
        var myDate = new Date(theTime)
        var year = myDate.getFullYear()
        var month = myDate.getMonth() + 1
        var full_month = myDate.getMonth() + 1
        if (month < 10) {
          full_month = '0' + month
        }
        var theDay = myDate.getDate()
        var full_Day = myDate.getDate()
        if (theDay < 10) {
          full_Day = '0' + theDay
        }
        var hours = myDate.getHours()
        var full_hours = myDate.getHours()
        if (hours < 10) {
          full_hours = '0' + hours
        }
        var minutes = myDate.getMinutes()
        var full_minutes = myDate.getMinutes()
        if (minutes < 10) {
          full_minutes = '0' + minutes
        }
        var seconds = myDate.getSeconds()
        var full_seconds = myDate.getSeconds()
        if (seconds < 10) {
          full_seconds = '0' + seconds
        }

        if (type == 'full') {
          return year + '-' + full_month + '-' + full_Day + ' ' + full_hours + ':' + full_minutes + ':' + full_seconds
        } else if (type == 's') {
          return year + '.' + month + '.' + theDay + ' ' + hours + ':' + minutes
        } else if (type == 'Ymdhs') {
          return year + '' + full_month + '' + full_Day + '' + full_hours + '' + full_minutes
        } else if (type == 'Ymdhms') {
          return year + '' + full_month + '' + full_Day + '' + full_hours + '' + full_minutes + '' + full_seconds
        } else {
          return myDate.getTime()
        }
      },

      /**
       * 格式化秒
       * @param int  value 总秒数
       * @return string result 格式化后的字符串
       */
      formatSeconds(value) {
        var theTime = parseInt(value)// 需要转换的时间秒
        var theTime1 = 0// 分
        var theTime2 = 0// 小时
        var theTime3 = 0// 天
        if (theTime > 60) {
          theTime1 = parseInt(theTime / 60)
          theTime = parseInt(theTime % 60)
          if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60)
            theTime1 = parseInt(theTime1 % 60)
            if (theTime2 > 24) {
              //大于24小时
              theTime3 = parseInt(theTime2 / 24)
              theTime2 = parseInt(theTime2 % 24)
            }
          }
        }
        var result = ''
        if (theTime > 0) {
          result = '' + parseInt(theTime) + '秒'
        }
        if (theTime1 > 0) {
          result = '' + parseInt(theTime1) + '分' + result
        }
        if (theTime2 > 0) {
          result = '' + parseInt(theTime2) + '小时' + result
        }
        if (theTime3 > 0) {
          result = '' + parseInt(theTime3) + '天' + result
        }
        return result
      },

      resetTimeAll() {
        console.log("1baseTimeSeconds==="+this.baseTimeSeconds)

        let setTime = this.timeSetH * 60 * 60 + this.timeSetM * 60 + this.timeSetS

        let baseDataSeconds = new Date(this.baseTimeDateString).getTime() / 1000
        this.baseTimeSeconds = setTime + baseDataSeconds

        // console.log("=====>"+new Date((this.baseTimeSeconds+parseInt(5678))*1000).toLocaleString())

        this.list.forEach((item, index) => {
          // item.playtime = this.formatSeconds(this.basetime+parseInt(item.videoleng));

          // item.playtime = this.baseTimeDateString+" "+this.myGetTime((this.baseTimeSeconds+parseInt(item.videoleng))*1000);

          this.baseTimeSeconds += parseInt(item.videoleng)
          // console.log(this.baseTimeSeconds+"  "+(MAX_TIME+baseDataSeconds));
          if (this.baseTimeSeconds > (MAX_TIME + baseDataSeconds)) {//超过了最大时长
            item.playtime = ''
            return false
          } else {
            item.playtime = this.myGetTime(this.baseTimeSeconds * 1000, 'full')
          }

        })
        console.log("2baseTimeSeconds==="+this.baseTimeSeconds)
      },

      changePlatform(label) {
        this.isSaveDrag(()=>{
          this.platformKey = label
        })


      },

      selectDate(sdate) {
        this.localDate = sdate
        // console.log('localDate==>' + this.localDate)
      },

      handleCloseProgramList(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {
          })
      },

      openProgramList() {
        this.getListProgram()
      },

      sortProgramList(a, b) {
        return Date.parse(a.setdate) - Date.parse(b.setdate)
      },

      /***
       *
       *节目排期列表，点击修改
       * */
      editProgramListData(item, index) {
        //根据节目排期 id 获取对应日期的详细视频编排
        let date = item.setdate
        this.localDate = date
        this.baseTimeHms = date
        this.currID_Date = item.id

        this.getList();//获取目标日期的节目单
        this.programList.sort(this.sortProgramList)

        this.programListDrawer = false
        this.baseTimeDateString = this.localDate//设置日期基数 YYYY-MM-DD
        this.baseTimeSeconds = new Date(this.baseTimeDateString).getTime() / 1000//日期基（秒）

        // this.$refs.programlist.closeDrawer();
      },


      /**
       * 删除节目单
       * */
      async handleDeleteProList(item, index) {

        const data = await delProgramList(item.id);
        if(data.code==20000){
          this.programList.splice(index, 1)
        }

      },

      createProgramBar() {

        if (this.programList.length < 30) {
          this.dialogAddProVisible = true
          this.localDateAdd = ''
        } else {
          this.$notify({
            title: '新增失败',
            message: '超出节目单最大容量',
            type: 'error',
            duration: 2000
          })
        }
      },

      closeAddProgramBar() {
        this.dialogAddProVisible = false
      },

      selectDateAddProBar(sdate) {
        this.localDateAdd = sdate
        // console.log('localDate==>' + this.localDate)
      },
      resetTempProList() {

      },

      /**
       * 新增节目单弹窗确定按钮
       */
      confirmAddProBar() {

        if(isEmpty(this.localDateAdd)){
          this.$notify({
            title: 'Error',
            message: '日期不能为空',
            type: 'error',
            duration: 2000
          })

          return false
        }
        // console.log("this.localDateAdd=="+this.localDateAdd)
        for (let i = 0; i < this.programList.length; i++) {
          let objList = eval(this.programList[i])
          if (objList.setdate == this.localDateAdd) {
            this.$notify({
              title: 'Error',
              message: '已存在相同日期的节目单',
              type: 'error',
              duration: 2000
            })
            return false
          }
        }

        this.dialogAddProVisible = false
        // this.localDate = this.localDateAdd;
        // this.programListDrawer = false;
        console.log('localDateAdd=' +parseTime(new Date()))
        this.tempProList = {
          id: '1',
          setdate: this.localDateAdd,
          playstate: 0,
          timelog: parseTime(new Date()),
          alivestate: 0,
          auther: '1'
        }

        updateProgramList(this.tempProList).then(
          (data) => {
          // const index = this.list.findIndex(v => v.id === this.temp.id)
          // this.list.splice(index, 1, this.temp)
          // this.dialogFormVisible = false
          //   console.log("updateProgramList.data=="+data.toString());

            if(data.code==20000){
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
              this.programList.push(this.tempProList)
            }



        }, ()=>{
          //fail
        })




      },

      delProBar(){},

      /////////////统一工具类/////////////////////////////

      handleResponse(response){
       // let ListJiemd =  response.data;
       let ListJiemd =[];
        for (let i in response.data) {
          ListJiemd.push(response.data[i])
        }
       console.log("handleResponse="+ ListJiemd[0])

        // const { importance, type, title, page = 1, limit = 20, sort } = response.query
        // let mockList = ListJiemd.filter(item => {
        //   if (importance && item.importance !== +importance) return false
        //   if (type && item.type !== type) return false
        //   if (title && item.title.indexOf(title) < 0) return false
        //   return true
        // })
        //
        // if (sort === '-id') {
        //   mockList = mockList.reverse()
        // }
        // const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))

        return {
          code: 20000,
          data: {
            total: ListJiemd.length,
            items: ListJiemd
          }
        }


      }


    }
  }
</script>

<style lang="scss">
  @import url("//unpkg.com/element-ui@2.13.2/lib/theme-chalk/index.css");

  .sortable-ghost {
    opacity: .8;
    color: #fff !important;
    background: #42b983 !important;
  }

  .app-container {
    padding: 20px;
  }

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }


  .dashboard {
    &-container {
      margin: 50px;
    }

    &-text {
      font-size: 40px;
      line-height: 46px;
    }
  }

  .filter-container {
    padding-bottom: 10px;
    width: 100%;
    height: 50px;
    /*background-color: bisque;*/

    .filter-item {
      display: inline-block;
      vertical-align: middle;
      margin-bottom: 10px;
    }
  }

  .infinite-list-item {
    list-style-type: none;
    margin-bottom: 3px;
    /*background-color: bisque;*/
    margin-left: 0px;
    padding: 0px;
    display: block;
  }

  .el-drawer.rtl {
    overflow: scroll
  }
</style>
<style scoped>
  .icon-star {
    margin-right: 2px;
  }

  .drag-handler {
    width: 20px;
    height: 20px;
    cursor: pointer;
  }

  .show-d {
    margin-top: 15px;
  }


</style>
